<template>
    <oa-page title="考勤打卡">
        <div class="top">
            <label class="name">{{username}}</label>
            <label class="time">{{date}}</label>
        </div>
        <div class="card-body">
            <div class="card-item">
                <div class="dot-container">
                    <label class="dot"></label>
                    <div class="dot-line">

                    </div>
                </div>
                <div class="card-container">
                    <label class="card-time">上班时间：09:00</label>
                    <div class="checked-card" v-if="start_item">
                        <div class="checked-time">
                            打卡时间{{start_item.time|hourTime}} <span v-if="start_item.warn &&start_item.warn_message != '外勤打卡'" class="warn">{{start_item.warn_message}}</span><span
                                v-if="!start_item.in_company" class="out">外勤</span>
                        </div>
                        <div class="checked-address">
                            <i class="oa-icon" :class="start_item.is_wifi ?'icon-wifi':'icon-dizhi'"></i>
                            {{start_item.address}}
                        </div>
                        <div class="checked-update" @click="updateCheck(false)">
                            更新打卡 <i class="oa-icon icon-jiantou"></i>
                        </div>
                    </div>
                    <div class="check-card" v-else>
                        <button class="btn-check" @click="checkClick(false)" :disabled="start_btn.disabled"
                                :class="{warn:start_btn.warn}">
                            <label class="btn-message">{{start_btn.message}}</label>
                            <label class="btn-time">{{now}}</label>
                        </button>
                        <div class="state-message">
                            <i class="oa-icon" :class="location.address && location.in_company?'icon-check-selected':'icon-warning warn'"></i>
                            <label class="state-in-location">{{location.in_check}}</label>
                        </div>
                        <div class="state-address">
                            {{location.address}}
                        </div>
                        <div class="reload-location" @click="checkInLocation">
                            重新定位
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-item">
                <div class="dot-container">
                    <label class="dot"></label>
                </div>
                <div class="card-container">
                    <label class="card-time">下班时间：18:00</label>
                    <div class="checked-card" v-if="end_item">
                        <div class="checked-time">
                            打卡时间{{end_item.time|hourTime}} <span v-if="end_item.warn && end_item.warn_message != '外勤打卡'" class="warn">{{end_item.warn_message}}</span><span
                                v-if="!end_item.in_company" class="out">外勤</span>
                        </div>
                        <div class="checked-address">
                            <i class="oa-icon" :class="end_item.is_wifi ?'icon-wifi':'icon-dizhi'"></i>
                            {{end_item.address}}
                        </div>
                        <div class="checked-update" @click="updateCheck(true)">
                            更新打卡 <i class="oa-icon icon-jiantou"></i>
                        </div>
                    </div>
                    <div class="check-card" v-if="start_item && !end_item">
                        <button @click="checkClick(true)" class="btn-check" :disabled="end_btn.disabled"
                                :class="{warn:end_btn.warn}">
                            <label class="btn-message">{{end_btn.message}}</label>
                            <label class="btn-time">{{now}}</label>
                        </button>
                        <div class="state-message">
                            <i class="oa-icon"
                               :class="location.address && location.in_company?'icon-check-selected':'icon-warning warn'"></i>
                            <label class="state-in-location">{{location.in_check}}</label>
                        </div>
                        <div class="state-address">
                            {{location.address}}
                        </div>
                        <div class="reload-location" @click="checkInLocation">
                            重新定位
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <transition enter-active-class="animated fadeIn"
                    leave-active-class="animated fadeOut">
            <div class="modal-mask" ref="mask" v-if="modal.show_modal">

            </div>
        </transition>
        <transition enter-active-class="animated bounceIn"
                    leave-active-class="animated bounceOut">
            <div class="modal-content" ref="mask" v-if="modal.show_modal">
                <div class="modal-dialog">
                    <label class="title">确定进行{{modal.warn_message}}</label>
                    <div class="card-time">
                        <div class="card-tips">
                            打卡时间：{{modal.card_time}}
                        </div>
                        <div class="card-tips">
                            打卡地址：{{location.address}}
                        </div>
                    </div>
                    <textarea v-model="modal.reason" placeholder=" 请填写打卡备注（选填） "></textarea>
                    <div class="btn-bottom">
                        <div class="btn-default" @click="modal.show_modal = false">
                            不打卡
                        </div>
                        <div class="btn-default" @click="uploadCardInfo(modal.is_warn,modal.warn_message)">
                            确定
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </oa-page>
</template>
<script>
    import OaPage from "../components/oa-page";
    import Coordinate, {getConfig, getTokenInfo, getUserInfo} from "../config";

    export default {
        components: {OaPage},
        name: 'Card',
        data() {
            return {

                modal: {
                    show_modal: false,
                    card_time: "",
                    reason: '',
                    is_start: false,
                    warn_message: '',
                    is_warn: false

                },

                username: "",
                date: "",
                // start_item:{
                //     time:"2018-3-7 18:01:18",
                //     address:"重庆市巴南区",
                //     is_warn:false,
                //     in_company:false,
                //     warn_message:"迟到打卡",
                //     is_wifi:false
                // },
                start_item: null,
                end_item: null,
                start_btn: {
                    message: "上班打卡",
                    warn: false,
                    disabled: true,
                    in_company: false,
                },
                end_btn: {
                    message: "上班打卡",
                    warn: false,
                    disabled: true,
                    in_company: false
                },
                location: {
                    in_wifi: false,
                    address: "",
                    in_check: "",
                    in_progress: false,
                    latitude: "",
                    longitude: "",
                    in_company: false
                },
                timer: null,
                now: ""
            }
        },
        mounted() {
            this.checkInLocation()
            // console.log(JSON.parse(this.$store.state.coordinate))
            let date = new Date();
            this.date = date.pattern("yyyy年M月dd日")
            this.username = getUserInfo().username
            this.timer = setInterval(this.updateTime, 1000);
            this.updateTime()
            this.clearData()
        },
        filters: {
            hourTime(time_string) {
                let date = time_string.convertDateFromString(time_string)
                return date.pattern("hh:mm")
            }
        },
        methods: {

            updateTime() {
                // let date = new Date();
                // this.date = date.pattern("yyyy年M月dd日")
                // this.username = getUserInfo().username
                // this.timer = setInterval(() => {
                let date = new Date();
                this.now = date.pattern("hh:mm:ss")
                if (date.getHours() > 9 || (date.getHours() == 9 && date.getMinutes() > 0)) {
                    this.start_btn.warn = true
                    this.start_btn.message = "迟到打卡"
                    this.start_btn.in_company = this.location.in_company
                } else if (this.location.in_company) {
                    this.start_btn.warn = false
                    this.start_btn.message = "上班打卡"
                    this.start_btn.in_company = this.location.in_company
                } else {
                    this.start_btn.warn = true
                    this.start_btn.message = "外勤打卡"

                }
                if (date.getHours() < 18) {
                    this.end_btn.warn = true
                    this.end_btn.message = "早退打卡"

                } else if (this.location.in_company) {
                    this.end_btn.warn = false
                    this.end_btn.message = "下班打卡"
                } else {
                    this.end_btn.warn = true
                    this.end_btn.message = "外勤打卡"
                }
                this.start_btn.in_company = this.location.in_company
                this.end_btn.in_company = this.location.in_company
                // }, 1000)
            },
            // checkUpload(is_end) {
            //     if (is_end) {
            //
            //     }
            // },
            updateCheck(is_end) {
                this.$createDialog({
                    type: 'confirm',
                    title: '提示',
                    content: '重新打卡会清空上次打卡记录，是否继续',
                    icon: 'cubeic-alert',
                    confirmBtn: {
                        text: '确认',
                    },
                    cancelBtn: {
                        text: '取消',
                    },
                    onConfirm: () => {
                        if (is_end) {
                            localStorage.removeItem("end_item")
                            this.end_item = null

                        } else {
                            localStorage.removeItem("start_item")
                            this.start_item = null
                        }
                        this.checkInLocation()
                    }
                }).show();

            },

            uploadCardInfo(is_warn, warn_message) {
                this.modal.show_modal = false
                let date = new Date()
                let config = getConfig();
                let tokenInfo = getTokenInfo();
                const toast = this.$createToast({
                    txt: '正在打卡',
                    type: 'loading',
                    time: 0,
                })
                toast.show();
                let url = config.rootUrl +
                    `/OA_Attendence/UserCard?type=app&Dcqtech_Token=${tokenInfo.token.TokenId}&in_out=${this.location.in_check ? 1 : 0}&lat=${this.location.latitude}&lon=${this.location.longitude}&address=${this.location.address}&why=${this.modal.reason}`;
                this.$get(url).then((res) => {
                    if (this.modal.is_start) {
                        let start_item = {
                            time: date.pattern("yyyy-MM-dd hh:mm:ss"),
                            warn: is_warn,
                            warn_message: warn_message,
                            address: this.location.address,
                            is_wifi: this.location.in_wifi,
                            in_company: this.location.in_company
                        }
                        localStorage.setItem("start_item", JSON.stringify(start_item))
                    } else {
                        let end_item = {
                            time: date.pattern("yyyy-MM-dd hh:mm:ss"),
                            warn: is_warn,
                            warn_message: warn_message,
                            address: this.location.address,
                            is_wifi: this.location.in_wifi,
                            in_company: this.location.in_company
                        }
                        localStorage.setItem("end_item", JSON.stringify(end_item))
                    }
                    toast.hide();
                    this.$createDialog({
                        type: 'alert',
                        title: '成功',
                        content: '打卡成功',
                        icon: 'cubeic-ok',
                        onConfirm: () => {
                            this.clearData()
                        }
                    }).show()
                }).catch((error) => {
                    toast.hide();
                    this.$createToast({
                        txt: '网络错误',
                        type: 'error',
                        time: 1500,
                    })
                })
            },
            clearData() {
                let start_item_string = localStorage.getItem("start_item")
                let start_item = JSON.parse(start_item_string)
                if (start_item) {
                    let day_string = start_item.time.convertDateFromString(start_item.time).pattern("yyyy-MM-dd")
                    let today = new Date().pattern("yyyy-MM-dd")
                    if (day_string != today) {
                        localStorage.removeItem("start_item")
                        this.start_item = null
                    } else {
                        this.start_item = start_item
                    }
                }
                let end_item_string = localStorage.getItem("end_item")
                let end_item = JSON.parse(end_item_string)
                if (end_item) {
                    let day_string = end_item.time.convertDateFromString(end_item.time).pattern("yyyy-MM-dd")
                    let today = new Date().pattern("yyyy-MM-dd")
                    if (day_string != today) {
                        localStorage.removeItem("end_item")
                        this.end_item = null
                    } else {
                        this.end_item = end_item
                    }
                }

            },


            checkInLocation() {
                try {
                    if (device.platform == "Android") {
                        WifiWizard.startScan(() => {
                            WifiWizard.getScanResults((res) => {
                                console.log(res)
                                this.checkWifi(res)
                            }, (error) => {
                                this.goLocation()
                            });
                            // alert(res)
                        }, (error) => {
                            this.goLocation()
                            console.log(error)
                        })
                    } else {
                        this.goLocation()
                    }

                } catch (e) {
                    console.log(e)
                    this.goLocation()
                }

            },

            checkWifi(res) {
                const wifiData = this.$store.state.coordinate.wifi
                if (res) {
                    res.forEach((item) => {
                        if (wifiData[item.BSSID]) {
                            this.location.in_company = true
                            this.location.in_wifi = true
                            this.location.in_check = "已进入WIFI打卡范围"
                            this.location.address = wifiData[item.BSSID]
                            this.start_btn.disabled = false
                            this.end_btn.disabled = false
                            return
                        }
                    })
                    if (!this.location.in_wifi) {
                        this.goLocation()
                    }
                } else {
                    this.goLocation()
                }
            },

            checkClick(is_end) {
                if (this.location.address) {
                    if (is_end && this.end_btn.warn) {
                        this.modal.card_time = new Date().pattern("yyyy-MM-dd hh:mm:ss")
                        this.modal.is_start = false
                        this.modal.is_warn = this.end_btn.warn
                        this.modal.warn_message = this.end_btn.message
                        this.modal.show_modal = true
                    } else if (is_end) {
                        this.modal.is_start = false
                        this.modal.is_warn = this.end_btn.warn
                        this.uploadCardInfo(false, "")
                    }

                    if (!is_end && this.start_btn.warn) {
                        this.modal.card_time = new Date().pattern("yyyy-MM-dd hh:mm:ss")

                        this.modal.is_start = true
                        this.modal.is_warn = this.start_btn.warn
                        this.modal.warn_message = this.start_btn.message
                        this.modal.show_modal = true
                    } else if (!is_end) {
                        this.modal.is_start = true
                        this.modal.is_warn = this.start_btn.warn
                        this.uploadCardInfo(false, "")
                    }
                }
            },

            inRang(range) {
                let IS_IN = false
                range.forEach((item) => {
                    if (this.location.longitude <= item.x1 && this.location.longitude >= item.x0 && this.location.latitude <= item.y1 && this.location.latitude >= item.y0) {
                        IS_IN = true
                        return
                    }
                })
                if (IS_IN) {
                    this.location.in_company = true
                    this.location.in_check = "已在考勤范围"
                } else {
                    this.location.in_company = false
                    this.location.in_check = "未在考勤范围"
                }
            },

            goLocation() {

                this.location.progress = true
                const toast = this.$createToast({
                    time: 0,
                    txt: '正在定位'
                })
                toast.show();
                setTimeout(() => {
                    try {
                        this.location.in_check = "GPS定位失败，请检查网络"
                        let Coordinate_range = this.$store.state.coordinate.range;
                        baidumap_location
                            .getCurrentPosition((result) => {
                                // console.log(JSON.stringify(result, null, 4));
                                //此处获取经纬度
                                console.log(result)
                                toast.hide()
                                this.location.progress = false
                                this.location.latitude = result.latitude;
                                this.location.longitude = result.longitude;
                                this.location.address = result.addr
                                this.inRang(Coordinate_range)
                                this.start_btn.disabled = false
                                this.end_btn.disabled = false

                            }, (error) => {
                                toast.hide();
                                this.location.in_company = false

                                this.start_btn.disabled = true
                                this.end_btn.disabled = true
                                this.location.progress = false
                                this.location.in_check = "GPS定位失败，请检查网络"
                            });
                    } catch (e) {
                        console.log(e);
                        toast.hide();
                        this.location.in_company = false

                        this.location.in_check = "GPS定位失败，请检查网络"
                        this.location.progress = false
                        this.start_btn.disabled = true
                        this.end_btn.disabled = true

                    }
                }, 100)

            }
        },

        beforeRouteLeave(to, form, next) {
            clearInterval(this.timer)
            console.log("离开了")
            next()
        }
        ,
    }
</script>
<style lang="less">
    .top {
        background: #ffffff;
        border-bottom: solid 1px #e0e0e0;
        height: 50px;
        padding: 0 12px;
        line-height: 50px;
        .name {
            color: #2c2c2c;
            font-size: 14px;
        }
        .time {
            float: right;
            color: #4a5c63;
            font-size: 14px;
        }
    }

    .modal-dialog {
        width: 320px;
        height: 340px;
        background: #fff;
        display: flex;
        flex-direction: column;
        .title {
            padding: 8px 12px;
            font-size: 18px;
            color: #2c2c2c;
            text-align: center;
        }
        .card-time {
            font-size: 14px;
            color: #2c2c2c;
            .card-tips {
                color: #888888;
                line-height: 32px;
                margin-left: 12px;
                margin-right: 12px;
            }
            background: #f0f0f0;
            border-bottom: solid 1px #e0e0e0;
            border-top: solid 1px #e0e0e0;
        }
        > textarea {
            flex: 1 0 auto;
            border: none;
            outline: none;
            padding: 10px;
            font-size: 16px;
            margin-left: 0;
            margin-right: 0;
            color: #2c2c2c;
            &::-webkit-input-placeholder {
                color: #888888;

            }
        }
        .btn-bottom {
            height: 44px;
            border-top: solid 1px #e0e0e0;
            line-height: 44px;
            display: flex;
            flex-direction: row;
            .btn-default {
                flex: 1;
                color: #41a6f0;
                font-size: 15px;
                text-align: center;
                &:active {
                    background: darken(#fff, 5%);
                }
                &:first-child {
                    border-right: solid 1px #e0e0e0;
                }
            }
        }
    }

    .modal-mask {
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        top: 0;
        z-index: 999;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
    }

    .modal-content {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 1000;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        top: 0;
        left: 0;
    }

    .card-body {
        background: #ffffff;
        padding: 12px;
        width: calc(~"100% - 24px");
        min-height: 140px;
        display: flex;
        flex-direction: column;
        .card-item {
            background: #ffffff;
            display: flex;
            min-height: 160px;
            flex-direction: row;
            .dot-container {
                flex: 0 1 auto;
                width: 40px;
                display: flex;
                flex-direction: column;
                align-items: center;
                .dot {
                    width: 12px;
                    height: 12px;
                    background: #41a6f0;
                    border-radius: 50%;

                }
                .dot-line {
                    width: 2px;
                    flex: 1;
                    background: #e0e0e0;
                }
            }
            .card-container {
                flex: 1;
                .card-time {
                    color: #888888;
                    font-size: 14px;
                }
                .checked-card {
                    .checked-time {
                        height: 40px;
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        font-size: 16px;
                        font-weight: 500;
                        color: #2c2c2c;
                        .warn {
                            margin-left: 10px;
                            font-size: 12px;
                            padding: 4px 8px;
                            border-radius: 3px;
                            border: solid 1px #e8864c;
                            color: #e8864c;
                        }
                        .out {
                            margin-left: 8px;
                            font-size: 12px;
                            padding: 4px 8px;
                            border-radius: 3px;
                            border: solid 1px #34b2e8;
                            color: #34b2e8;
                        }
                    }
                    .checked-address {
                        font-size: 12px;
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        color: #888888;
                        .icon-dizhi {
                            font-size: 16px;
                            margin-right: 8px;
                        }
                        .icon-wifi {
                            font-size: 16px;
                            margin-right: 8px;
                        }
                    }
                    .checked-update {
                        font-size: 14px;
                        color: #41a6f0;
                        line-height: 32px;
                        &:active {
                            color: darken(#41a6f0, 10%);
                        }

                    }
                }
                .check-card {
                    padding: 10px;
                    flex-direction: column;
                    align-items: center;
                    display: flex;
                    .btn-check {
                        width: 140px;
                        margin-right: 40px;
                        border-radius: 50%;
                        outline: none;
                        height: 140px;

                        border: solid 0px transparent;
                        background: linear-gradient(#41a6f0, #1390eb);
                        color: #ffffff;

                        .btn-message {
                            font-size: 20px;
                        }
                        .btn-time {
                            margin-top: 8px;
                            font-size: 14px;
                            color: #f0f0f0;
                        }

                        &:active {
                            background: lighten(#41a6f0, 10%);
                        }
                        &.warn {
                            background: linear-gradient(#fc9153, #fcb552);
                            &:active {
                                background: lighten(#fc9153, 10%);
                            }
                        }
                        &:disabled {
                            background: linear-gradient(#8a8683, #857f7b);
                            &:active {
                                background: lighten(#8a8683, 10%);
                            }
                        }

                    }
                    .state-message {
                        margin-right: 40px;
                        font-size: 12px;
                        color: #4a4c5b;
                        display: flex;
                        flex-direction: row;
                        height: 40px;
                        align-items: center;

                        .oa-icon {
                            font-size: 16px;
                            color: #39b338;
                            align-self: center;
                            margin-right: 6px;
                            &.warn {
                                color: #e8864c;
                            }
                        }

                    }
                    .reload-location {
                        margin-right: 40px;
                        line-height: 28px;
                        color: #41a6f0;
                        font-size: 14px;
                        :active {
                            color: darken(#41a6f0, 10%);
                        }
                    }
                    .state-address {
                        font-size: 14px;
                        color: #4a4c5b;
                        margin: 4px;
                        margin-right: 40px;
                    }
                }
            }
        }

    }

</style>